﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace TorchView.Game
{
  public static class Torchlight
  {
    const int SteamApplicationID = 41500;

    public const string SavedGameExtension = "svt";
    public static readonly string InstallDirectory;
    public static readonly string Executable;
    public static readonly string SaveDirectory;

    static Torchlight()
    {
      InstallDirectory = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Runic Games\Torchlight").GetValue("InstDir") as string;
      Executable = Path.Combine(InstallDirectory, "torchlight.exe");
      SaveDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\runic games\torchlight\save";
    }

    /// <summary>
    /// Run the torchlight game
    /// </summary>
    /// <returns>true if the game was launched, false if it failed</returns>
    public static bool Run()
    {
      return TryRunningThroughSteam()
        || TryRunningDirectly();
    }

    // This has not been tested
    private static bool TryRunningDirectly()
    {
      if (File.Exists(Executable))
      {
        Process.Start(Executable);
        return true;
      }
      return false;
    }

    private static bool TryRunningThroughSteam()
    {
      int index = InstallDirectory.IndexOf("steamapps");
      if (index != -1)
      {
        ProcessStartInfo startInfo = new ProcessStartInfo(InstallDirectory.Substring(0, index) + "steam.exe", "-applaunch " + SteamApplicationID);
        startInfo.UseShellExecute = false;
        Process.Start(startInfo);
        return true;
      }
      return false;
    }
  }
}
